package com.hassean.we.admin.common.util;

import com.google.common.io.Files;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.List;
public class WebFileUtil {
    
    /**
     * 创建文件夹
     * @param dFile
     */
    public static void createFold(File dFile) {
		if (!dFile.exists()) dFile.mkdirs();
	}
    

    /**
     * 
     * <B>方法描述：</B>（读取文件文本内容 ） <br/>
     *
     * <B>创建日期：</B> 2014年6月14日 上午10:43:41 
     * @param filepath
     * @return
     */
    public static String readFile(String filepath) {
    	
    	String content = "";
    	
    	File file = new File(filepath);
    	
    	if (!file.exists()) return content;
    	
    	try {
			
    		List<String> lines = Files.readLines(file, Charset.forName("UTF-8"));
    		for (String line : lines)
    			content = content + line + "\n";
		} catch (Exception e) {
			e.printStackTrace();

		}
    	
    	return content;
    }
    
   /***
    *
    * @param response
    * @param url         下载文件的相对路径
    * @param fileName    下载文件名字
    */
    public static void downloadFile(HttpServletResponse response, String url, String fileName){
    	
    	String root =null;
    	
    	fileName = fileName + url.substring(url.lastIndexOf("."));
    	System.out.println(fileName);
    	try {
	    	fileName = new String(fileName.getBytes(), "iso8859-1");//解决中文 文件名问题  
	    	response.setContentType("application/octet-stream"); 
	    	response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); 
		 
			OutputStream os = response.getOutputStream(); 
			String realFilePath2 = root + url;
            String realFilePath =  "F:\\终端导入模板.xls";

			realFilePath = realFilePath.replace("\\", "/");
			FileInputStream fis = new FileInputStream(new File(realFilePath)); 
			byte[] b = new byte[1024]; 
			int i = 0; 
			
			while ( (i = fis.read(b)) > 0 ) { 
				os.write(b, 0, i);
			}
			fis.close(); 
			os.flush(); 
			os.close(); 
		} catch ( Exception e ) { 
		} 
    	
    }
    /**
     * 
     * @param targetPath      路径 
     * @param fileName        文件名
     * @param tarFileContent  内容
     */
    public static void writeFile(String targetPath,String fileName,String tarFileContent){
    	
    	File file = new File(targetPath);
    	if(!file.exists()){
    		file.mkdirs();
    	}
    	FileWriter writer = null;
        try {
             writer = new FileWriter(targetPath+fileName);
             writer.write(tarFileContent);
        } catch (Exception e) {
             e.printStackTrace();
        } finally {
             if (writer != null) {
                 try {
                     writer.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
    	
    }

}
